home *** CD-ROM | disk | FTP | other *** search
/ Programming Microsoft Visual Basic .NET / Programming Microsoft Visual Basic .NET (Microsoft Press)(X08-78517)(2002).bin / setup / vbnet / 19 advanced win32 techniques / win32techniquesdemo / processform.vb < prev    next >
Encoding:
Text File  |  2002-03-16  |  17.3 KB  |  432 lines

  1. Imports System.Diagnostics
  2.  
  3. Public Class ProcessForm
  4.     Inherits System.Windows.Forms.Form
  5.  
  6. #Region " Windows Form Designer generated code "
  7.  
  8.     Public Sub New()
  9.         MyBase.New()
  10.  
  11.         'This call is required by the Windows Form Designer.
  12.         InitializeComponent()
  13.  
  14.         'Add any initialization after the InitializeComponent() call
  15.  
  16.     End Sub
  17.  
  18.     'Form overrides dispose to clean up the component list.
  19.     Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
  20.         If disposing Then
  21.             If Not (components Is Nothing) Then
  22.                 components.Dispose()
  23.             End If
  24.         End If
  25.         MyBase.Dispose(disposing)
  26.     End Sub
  27.         Friend WithEvents Button1 As System.Windows.Forms.Button
  28.     Friend WithEvents Button2 As System.Windows.Forms.Button
  29.     Friend WithEvents Button3 As System.Windows.Forms.Button
  30.     Friend WithEvents OpenFileDialog1 As System.Windows.Forms.OpenFileDialog
  31.     Friend WithEvents txtOutput As System.Windows.Forms.TextBox
  32.     Friend WithEvents Button4 As System.Windows.Forms.Button
  33.     Friend WithEvents Button5 As System.Windows.Forms.Button
  34.     Friend WithEvents lstProcesses As System.Windows.Forms.ListBox
  35.     Friend WithEvents Button6 As System.Windows.Forms.Button
  36.     Friend WithEvents Button7 As System.Windows.Forms.Button
  37.         Friend WithEvents lblMessage As System.Windows.Forms.Label
  38.     
  39.     'Required by the Windows Form Designer
  40.     Private components As System.ComponentModel.Container
  41.  
  42.     'NOTE: The following procedure is required by the Windows Form Designer
  43.     'It can be modified using the Windows Form Designer.  
  44.     'Do not modify it using the code editor.
  45.     <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
  46.         Me.OpenFileDialog1 = New System.Windows.Forms.OpenFileDialog()
  47.         Me.Button4 = New System.Windows.Forms.Button()
  48.         Me.Button5 = New System.Windows.Forms.Button()
  49.         Me.Button6 = New System.Windows.Forms.Button()
  50.         Me.Button7 = New System.Windows.Forms.Button()
  51.         Me.lstProcesses = New System.Windows.Forms.ListBox()
  52.         Me.Button1 = New System.Windows.Forms.Button()
  53.         Me.Button2 = New System.Windows.Forms.Button()
  54.         Me.Button3 = New System.Windows.Forms.Button()
  55.         Me.txtOutput = New System.Windows.Forms.TextBox()
  56.         Me.lblMessage = New System.Windows.Forms.Label()
  57.         Me.SuspendLayout()
  58.         '
  59.         'Button4
  60.         '
  61.         Me.Button4.Location = New System.Drawing.Point(16, 304)
  62.         Me.Button4.Name = "Button4"
  63.         Me.Button4.Size = New System.Drawing.Size(144, 40)
  64.         Me.Button4.TabIndex = 3
  65.         Me.Button4.Text = "Close the process"
  66.         '
  67.         'Button5
  68.         '
  69.         Me.Button5.Location = New System.Drawing.Point(16, 160)
  70.         Me.Button5.Name = "Button5"
  71.         Me.Button5.Size = New System.Drawing.Size(144, 40)
  72.         Me.Button5.TabIndex = 3
  73.         Me.Button5.Text = "Info on current process"
  74.         '
  75.         'Button6
  76.         '
  77.         Me.Button6.Location = New System.Drawing.Point(16, 208)
  78.         Me.Button6.Name = "Button6"
  79.         Me.Button6.Size = New System.Drawing.Size(144, 40)
  80.         Me.Button6.TabIndex = 3
  81.         Me.Button6.Text = "Info on running processes"
  82.         '
  83.         'Button7
  84.         '
  85.         Me.Button7.Location = New System.Drawing.Point(16, 256)
  86.         Me.Button7.Name = "Button7"
  87.         Me.Button7.Size = New System.Drawing.Size(144, 40)
  88.         Me.Button7.TabIndex = 3
  89.         Me.Button7.Text = "Search process"
  90.         '
  91.         'lstProcesses
  92.         '
  93.         Me.lstProcesses.Anchor = ((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
  94.                     Or System.Windows.Forms.AnchorStyles.Right)
  95.         Me.lstProcesses.ItemHeight = 18
  96.         Me.lstProcesses.Location = New System.Drawing.Point(176, 16)
  97.         Me.lstProcesses.Name = "lstProcesses"
  98.         Me.lstProcesses.Size = New System.Drawing.Size(368, 94)
  99.         Me.lstProcesses.Sorted = True
  100.         Me.lstProcesses.TabIndex = 4
  101.         '
  102.         'Button1
  103.         '
  104.         Me.Button1.Location = New System.Drawing.Point(16, 16)
  105.         Me.Button1.Name = "Button1"
  106.         Me.Button1.Size = New System.Drawing.Size(144, 40)
  107.         Me.Button1.TabIndex = 0
  108.         Me.Button1.Text = "Load Autoexec.bat in Notepad"
  109.         '
  110.         'Button2
  111.         '
  112.         Me.Button2.Location = New System.Drawing.Point(16, 64)
  113.         Me.Button2.Name = "Button2"
  114.         Me.Button2.Size = New System.Drawing.Size(144, 40)
  115.         Me.Button2.TabIndex = 0
  116.         Me.Button2.Text = "Load a document"
  117.         '
  118.         'Button3
  119.         '
  120.         Me.Button3.Location = New System.Drawing.Point(16, 112)
  121.         Me.Button3.Name = "Button3"
  122.         Me.Button3.Size = New System.Drawing.Size(144, 40)
  123.         Me.Button3.TabIndex = 1
  124.         Me.Button3.Text = "Redirect Find output"
  125.         '
  126.         'txtOutput
  127.         '
  128.         Me.txtOutput.Anchor = (((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
  129.                     Or System.Windows.Forms.AnchorStyles.Left) _
  130.                     Or System.Windows.Forms.AnchorStyles.Right)
  131.         Me.txtOutput.Location = New System.Drawing.Point(176, 128)
  132.         Me.txtOutput.Multiline = True
  133.         Me.txtOutput.Name = "txtOutput"
  134.         Me.txtOutput.ScrollBars = System.Windows.Forms.ScrollBars.Both
  135.         Me.txtOutput.Size = New System.Drawing.Size(368, 184)
  136.         Me.txtOutput.TabIndex = 2
  137.         Me.txtOutput.Text = ""
  138.         Me.txtOutput.WordWrap = False
  139.         '
  140.         'lblMessage
  141.         '
  142.         Me.lblMessage.Anchor = ((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left) _
  143.                     Or System.Windows.Forms.AnchorStyles.Right)
  144.         Me.lblMessage.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
  145.         Me.lblMessage.Location = New System.Drawing.Point(176, 320)
  146.         Me.lblMessage.Name = "lblMessage"
  147.         Me.lblMessage.Size = New System.Drawing.Size(368, 24)
  148.         Me.lblMessage.TabIndex = 6
  149.         '
  150.         'ProcessForm
  151.         '
  152.         Me.AutoScaleBaseSize = New System.Drawing.Size(7, 17)
  153.         Me.ClientSize = New System.Drawing.Size(552, 349)
  154.         Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.lblMessage, Me.Button7, Me.Button6, Me.lstProcesses, Me.Button5, Me.Button4, Me.txtOutput, Me.Button3, Me.Button2, Me.Button1})
  155.         Me.Font = New System.Drawing.Font("Microsoft Sans Serif", 11!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
  156.         Me.Name = "ProcessForm"
  157.         Me.Text = "Processes"
  158.         Me.ResumeLayout(False)
  159.  
  160.     End Sub
  161.  
  162. #End Region
  163.  
  164.     ' run Notepad and list environment variables
  165.  
  166.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  167.         Dim proc As New Process()
  168.         ' Prepare to run Notepad and load C:\Autoexec.it in it.
  169.         proc.StartInfo.FileName = "Notepad.exe"
  170.         ' get the name of the C:\WINDOWS directory
  171.         proc.StartInfo.WorkingDirectory = IO.Path.GetDirectoryName(Environment.SystemDirectory)
  172.         proc.StartInfo.Arguments = "c:\autoexec.bat"
  173.  
  174.         ' List all environment variables.
  175.         Dim de As DictionaryEntry
  176.         For Each de In proc.StartInfo.EnvironmentVariables
  177.             Debug.WriteLine(de.Key.ToString & "=" & de.Value.ToString)
  178.         Next
  179.  
  180.         ' ensure that error dialogs are displayed correctly.
  181.         proc.StartInfo.ErrorDialog = True
  182.         proc.StartInfo.ErrorDialogParentHandle = Me.Handle
  183.         proc.StartInfo.UseShellExecute = False
  184.  
  185.         ' run it.
  186.         proc.Start()
  187.     End Sub
  188.  
  189.     ' run an executable associated with a file extension
  190.  
  191.     Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
  192.         Dim proc As New Process()
  193.  
  194.         OpenFileDialog1.CheckFileExists = True
  195.         OpenFileDialog1.Filter = "All Files|*.*"
  196.         If OpenFileDialog1.ShowDialog = DialogResult.OK Then
  197.  
  198.             ' Prepare to run Notepad and load C:\Autoexec.it in it.
  199.             proc.StartInfo.FileName = OpenFileDialog1.FileName
  200.             proc.StartInfo.ErrorDialog = True
  201.             proc.StartInfo.ErrorDialogParentHandle = Me.Handle
  202.  
  203.             Try
  204.                 proc.Start()
  205.             Catch ex As Exception
  206.                 MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
  207.                 Exit Sub
  208.             End Try
  209.         End If
  210.  
  211. #Const WAIT_UNTIL_PROCESS_ENDS = False
  212.  
  213. #If WAIT_UNTIL_PROCESS_ENDS Then
  214.         proc.WaitForExit()
  215.         lblMessage.Text = "Application has exited - Exit code = " & proc.ExitCode.ToString
  216.         Beep()
  217. #End If
  218.  
  219.     End Sub
  220.  
  221.     ' demonstrates how you can call a command-line program
  222.     ' and process its output
  223.  
  224.     Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
  225.         Dim proc As New Process()
  226.  
  227.         ' Search all the lines in C:\AUTOEXEC.BAT that contain a "x" character.
  228.         proc.StartInfo.FileName = "find ""x"""
  229.         proc.StartInfo.Arguments = "c:\autoexec.bat"
  230.         ' UseShellExecute must be False.
  231.         proc.StartInfo.UseShellExecute = False
  232.         ' Redirect the standard output channel.
  233.         proc.StartInfo.RedirectStandardOutput = True
  234.         ' Suppress the creation of the console window.
  235.         proc.StartInfo.CreateNoWindow = True
  236.         proc.Start()
  237.  
  238.         ' Get the StreamReader that points to output data.
  239.         Dim sr As System.IO.StreamReader = proc.StandardOutput
  240.         ' Display the output data in a TextBox control.
  241.         txtOutput.Text = sr.ReadToEnd
  242.         ' Close the stream.
  243.         sr.Close()
  244.     End Sub
  245.  
  246.     ' check whether a process is responding, and kill it
  247.  
  248.     Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
  249.         ' Exit if no selected process.
  250.         If lstProcesses.SelectedItem Is Nothing Then Exit Sub
  251.  
  252.         ' Get a reference to the highlighted process.
  253.         Dim proc As Process = CType(lstProcesses.SelectedItem, Process)
  254.         Try
  255.             If proc.Responding Then
  256.                 proc.CloseMainWindow()
  257.             Else
  258.                 proc.Kill()
  259.             End If
  260.         Catch ex As Exception
  261.             MessageBox.Show(ex.Message, "Unable to Kill")
  262.         End Try
  263.     End Sub
  264.  
  265.     ' Display information on current process.
  266.  
  267.     Private Sub Button5_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button5.Click
  268.         txtOutput.Text = GetProcessInfo(Process.GetCurrentProcess)
  269.     End Sub
  270.  
  271.     ' load info on all running processes
  272.  
  273.     Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
  274.         Dim p As Process
  275.         ' This is necessary to cope with Processes that don't allow to trap events from.
  276.         On Error Resume Next
  277.         ' unbind processes from event handlers.
  278.         For Each p In lstProcesses.Items
  279.             RemoveHandler p.Exited, AddressOf Process_Exited
  280.         Next
  281.         ' Clear listbox elements.
  282.         lstProcesses.Items.Clear()
  283.  
  284.         ' Display ProcessName property in the list area.
  285.         lstProcesses.DisplayMember = "ProcessName"
  286.  
  287.         ' Load info on all running process in the ListBox control.
  288.         For Each p In Process.GetProcesses
  289.             lstProcesses.Items.Add(p)
  290.             ' Bind each element to the event handler.
  291.             AddHandler p.Exited, AddressOf Process_Exited
  292.             p.EnableRaisingEvents = True
  293.         Next
  294.  
  295.         ' display info on first process
  296.         lstProcesses.SelectedIndex = 0
  297.     End Sub
  298.  
  299.     ' get array of all processes with a given name
  300.  
  301.     Private Sub Button7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button7.Click
  302.         ' ask for a process name - defaults to Notepad
  303.         Dim procName As String
  304.         procName = InputBox("Enter the name of a process", "Search Process", "notepad")
  305.         If procName = "" Then Exit Sub
  306.  
  307.         ' get an array with all processes with that name.
  308.         Dim procs() As Process = Process.GetProcessesByName(procName)
  309.         If procs.Length = 0 Then
  310.             MessageBox.Show("Process not found", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
  311.             Exit Sub
  312.         End If
  313.  
  314.         ' This is necessary to cope with Processes that don't allow to trap events from.
  315.         On Error Resume Next
  316.  
  317.         Dim p As Process
  318.         ' unbind processes from event handlers.
  319.         For Each p In lstProcesses.Items
  320.             RemoveHandler p.Exited, AddressOf Process_Exited
  321.         Next
  322.         ' Clear listbox elements.
  323.         lstProcesses.Items.Clear()
  324.  
  325.         ' Display ProcessName property in the list area.
  326.         lstProcesses.DisplayMember = "ProcessName"
  327.  
  328.         ' Load info on matching processes in the ListBox control.
  329.         For Each p In procs
  330.             lstProcesses.Items.Add(p)
  331.             AddHandler p.Exited, AddressOf Process_Exited
  332.             p.EnableRaisingEvents = True
  333.         Next
  334.         ' display info on first process
  335.         lstProcesses.SelectedIndex = 0
  336.     End Sub
  337.  
  338.     ' This routine is invoked when one of the watched process terminates
  339.  
  340.     Private Sub Process_Exited(ByVal sender As Object, ByVal e As EventArgs)
  341.         ' Get a reference to the process in question.
  342.         Dim proc As Process = CType(sender, Process)
  343.         lblMessage.Text = String.Format("Process {0} has exited - Exit code is {1}", proc.Id, proc.ExitCode)
  344.         Beep()
  345.     End Sub
  346.  
  347.     ' Display information on selected process.
  348.  
  349.     Private Sub lstProcesses_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstProcesses.SelectedIndexChanged
  350.         ' Get the selected process.
  351.         Dim proc As Process = CType(lstProcesses.SelectedItem, Process)
  352.         ' Display information on this process.
  353.         txtOutput.Text = GetProcessInfo(proc)
  354.     End Sub
  355.  
  356.     ' Return a string describing a process.
  357.     Function GetProcessInfo(ByVal proc As Process) As String
  358.         Dim res As String
  359.         Dim crlf As String = ControlChars.CrLf
  360.         Dim mo As ProcessModule
  361.         Dim th As ProcessThread
  362.  
  363.         ' Ignore properties that raise an error.
  364.         On Error Resume Next
  365.  
  366.         ' Ensure data is up-to-date.
  367.         proc.Refresh()
  368.  
  369.         res &= "=== PROCESS " & proc.ProcessName & crlf
  370.         res &= "ID = " & proc.Id & crlf
  371.         res &= "BasePriority = " & proc.BasePriority.ToString & crlf
  372.         ' Get main window information.
  373.         res &= "MainWindowTitle = " & proc.MainWindowTitle & crlf
  374.         res &= "MainWindowHandle = " & Hex(proc.MainWindowHandle.ToInt32) & crlf
  375.         res &= crlf
  376.  
  377.         ' Get time information.
  378.         res &= "StartTime = " & proc.StartTime.ToString & crlf
  379.         res &= "UserProcessorTime = " & proc.UserProcessorTime.ToString & crlf
  380.         res &= "PrivilegedProcessorTime = " & proc.PrivilegedProcessorTime.ToString & crlf
  381.         res &= "TotalProcessorTime = " & proc.TotalProcessorTime.ToString & crlf
  382.         res &= crlf
  383.  
  384.         ' Get Working set information.
  385.         res &= "WorkingSet = " & proc.WorkingSet.ToString & crlf
  386.         res &= "MinWorkingSet = " & proc.MinWorkingSet.ToString & crlf
  387.         res &= "MaxWorkingSet = " & proc.MaxWorkingSet.ToString & crlf
  388.         res &= "PeakWorkingSet = " & proc.PeakWorkingSet & crlf
  389.         res &= crlf
  390.  
  391.         ' Get memory information.
  392.         res &= "VirtualMemorySize = " & proc.VirtualMemorySize & crlf
  393.         res &= "NonpagedSystemMemorySize = " & proc.NonpagedSystemMemorySize & crlf
  394.         res &= "PagedMemorySize = " & proc.PagedMemorySize & crlf
  395.         res &= "PagedSystemMemorySize = " & proc.PagedSystemMemorySize & crlf
  396.         res &= "PeakPagedMemorySize = " & proc.PeakPagedMemorySize & crlf
  397.         res &= "PeakVirtualMemorySize = " & proc.PeakVirtualMemorySize & crlf
  398.         res &= "PrivateMemorySize = " & proc.PrivateMemorySize & crlf
  399.         res &= crlf
  400.  
  401.  
  402.         ' Get information on all modules
  403.         res &= "MODULES : " & crlf
  404.         res &= "MainModule = " & proc.MainModule.ModuleName & crlf
  405.  
  406.         For Each mo In proc.Modules
  407.             res &= "   Module Name = " & mo.ModuleName & crlf
  408.             res &= "      FileName = " & mo.FileName & crlf
  409.             res &= "      BaseAddress = " & Hex(mo.BaseAddress.ToInt32) & crlf
  410.             res &= "      Version = " & mo.FileVersionInfo.FileVersion & crlf
  411.             res &= "      Memory size = " & mo.ModuleMemorySize & crlf
  412.         Next
  413.         res &= crlf
  414.  
  415.         ' Get information on all threads.
  416.         res &= "THREADS : " & crlf
  417.         For Each th In proc.Threads
  418.             res &= "   Thread ID = " & th.Id.ToString & crlf
  419.             res &= "      StartTime = " & th.StartTime.ToString & crlf
  420.             res &= "      BasePriority = " & th.BasePriority & crlf
  421.             res &= "      PriorityLevel = " & th.PriorityLevel & crlf
  422.             res &= "      ThreadState = " & th.ThreadState.ToString & crlf
  423.             res &= "      UserProcessorTime = " & th.UserProcessorTime.ToString & crlf
  424.             res &= "      TotalProcessorTime = " & th.TotalProcessorTime.ToString & crlf
  425.         Next
  426.         res &= crlf
  427.  
  428.         Return res
  429.     End Function
  430.  
  431. End Class
  432.